package os_1;

import java.util.*;

public class os_1_1 {
    public static void main(String[] args) {
        // 创建6个进程
        List<Process> processes = new ArrayList<>();
        processes.add(new Process("Process 1", 5, 3));
        processes.add(new Process("Process 2", 3, 5));
        processes.add(new Process("Process 3", 1, 2));
        processes.add(new Process("Process 4", 4, 4));
        processes.add(new Process("Process 5", 2, 6));
        processes.add(new Process("Process 6", 6, 1));

        // 按优先权从大到小排序
        processes.sort((p1, p2) -> p2.priority - p1.priority);

        // 调度进程
        while (!processes.isEmpty()) {
            Process currentProcess = processes.get(0);
            System.out.println("Selected Process: " + currentProcess.name);
            currentProcess.run();

            // 更新优先权和运行时间
            currentProcess.priority--;
            currentProcess.time--;

            // 如果运行时间为0，则移除进程
            if (currentProcess.time == 0) {
                processes.remove(currentProcess);
            } else {
                // 重新排序
                processes.sort((p1, p2) -> p2.priority - p1.priority);
            }

            // 显示当前进程状态
            System.out.println("Current Process States:");
            for (Process p : processes) {
                System.out.println(p);
            }
            System.out.println();
        }

        System.out.println("All processes have finished.");
    }

    static class Process {
        String name;
        int priority;
        int time;

        public Process(String name, int priority, int time) {
            this.name = name;
            this.priority = priority;
            this.time = time;
        }

        public void run() {
            System.out.println(name + " is running.");
            // 模拟进程执行时间
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(name + " has finished this round.");
        }

        @Override
        public String toString() {
            return "Process{" +
                    "name='" + name + '\'' +
                    ", priority=" + priority +
                    ", time=" + time +
                    '}';
        }
    }
}